# 资产调拨相关视图
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q, Count, Sum
from django.http import JsonResponse
from django.utils import timezone
from django.views.decorators.http import require_http_methods
from django.db import transaction

from .models import Asset, Department, Location
from .models_transfer import AssetTransfer, AssetTransferItem, TransferApprovalFlow
from .models_system import SystemLog
from django.contrib.auth.models import User


@login_required
def transfer_list(request):
    """调拨申请列表"""
    transfers = AssetTransfer.objects.select_related(
        'applicant', 'applicant_department', 'target_department', 'approver'
    ).prefetch_related('transfer_items').all()
    
    # 筛选条件
    status_filter = request.GET.get('status')
    type_filter = request.GET.get('type')
    applicant_filter = request.GET.get('applicant')
    date_from = request.GET.get('date_from')
    date_to = request.GET.get('date_to')
    search_query = request.GET.get('search')
    
    if status_filter:
        transfers = transfers.filter(status=status_filter)
    
    if type_filter:
        transfers = transfers.filter(transfer_type=type_filter)
    
    if applicant_filter:
        transfers = transfers.filter(applicant_id=applicant_filter)
    
    if date_from:
        transfers = transfers.filter(created_at__date__gte=date_from)
    
    if date_to:
        transfers = transfers.filter(created_at__date__lte=date_to)
    
    if search_query:
        transfers = transfers.filter(
            Q(transfer_number__icontains=search_query) |
            Q(title__icontains=search_query) |
            Q(reason__icontains=search_query)
        )
    
    # 分页
    paginator = Paginator(transfers, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 统计信息
    stats = {
        'total': transfers.count(),
        'pending': transfers.filter(status='pending').count(),
        'approved': transfers.filter(status='approved').count(),
        'in_transit': transfers.filter(status='in_transit').count(),
        'completed': transfers.filter(status='completed').count(),
    }
    
    context = {
        'page_obj': page_obj,
        'stats': stats,
        'status_choices': AssetTransfer.TRANSFER_STATUS_CHOICES,
        'type_choices': AssetTransfer.TRANSFER_TYPE_CHOICES,
        'status_filter': status_filter,
        'type_filter': type_filter,
        'applicant_filter': applicant_filter,
        'date_from': date_from,
        'date_to': date_to,
        'search_query': search_query,
    }
    
    return render(request, 'assets/transfer/transfer_list.html', context)


@login_required
def transfer_create(request):
    """创建调拨申请"""
    if request.method == 'POST':
        title = request.POST.get('title')
        transfer_type = request.POST.get('transfer_type')
        reason = request.POST.get('reason')
        description = request.POST.get('description', '')
        priority = request.POST.get('priority', 'medium')
        expected_completion_date = request.POST.get('expected_completion_date')
        
        target_department_id = request.POST.get('target_department')
        target_location_id = request.POST.get('target_location')
        target_user_id = request.POST.get('target_user')
        estimated_cost = request.POST.get('estimated_cost')
        
        asset_ids = request.POST.getlist('assets')
        
        if not asset_ids:
            messages.error(request, '请选择要调拨的资产')
            return render(request, 'assets/transfer/transfer_form.html', {
                'departments': Department.objects.all(),
                'locations': Location.objects.all(),
                'users': User.objects.all(),
                'assets': Asset.objects.filter(status__in=['idle', 'in_use']),
            })
        
        try:
            with transaction.atomic():
                # 创建调拨申请
                transfer = AssetTransfer.objects.create(
                    title=title,
                    transfer_type=transfer_type,
                    reason=reason,
                    description=description,
                    priority=priority,
                    applicant=request.user,
                    applicant_department=request.user.profile.department if hasattr(request.user, 'profile') else None,
                    target_department_id=target_department_id if target_department_id else None,
                    target_location_id=target_location_id if target_location_id else None,
                    target_user_id=target_user_id if target_user_id else None,
                    estimated_cost=estimated_cost if estimated_cost else None,
                    expected_completion_date=expected_completion_date,
                    status='draft'
                )
                
                # 创建调拨项目
                for asset_id in asset_ids:
                    asset = Asset.objects.get(id=asset_id)
                    AssetTransferItem.objects.create(
                        transfer=transfer,
                        asset=asset
                    )
                
                # 记录系统日志
                SystemLog.log(
                    level='INFO',
                    module='asset',
                    action='transfer_create',
                    message=f'创建资产调拨申请: {transfer.transfer_number}',
                    user=request.user,
                    request=request,
                    details={'transfer_id': transfer.id, 'asset_count': len(asset_ids)}
                )
                
                messages.success(request, f'调拨申请 {transfer.transfer_number} 创建成功')
                return redirect('assets:transfer_detail', pk=transfer.pk)
                
        except Exception as e:
            messages.error(request, f'创建调拨申请失败: {str(e)}')
    
    context = {
        'departments': Department.objects.all(),
        'locations': Location.objects.all(),
        'users': User.objects.all(),
        'assets': Asset.objects.filter(status__in=['idle', 'in_use']).select_related('category', 'department', 'location'),
        'transfer_types': AssetTransfer.TRANSFER_TYPE_CHOICES,
        'priorities': AssetTransfer.PRIORITY_CHOICES,
    }
    
    return render(request, 'assets/transfer/transfer_form.html', context)


@login_required
def transfer_detail(request, pk):
    """调拨申请详情"""
    transfer = get_object_or_404(
        AssetTransfer.objects.select_related(
            'applicant', 'applicant_department', 'target_department', 
            'target_location', 'target_user', 'approver', 'executor'
        ).prefetch_related(
            'transfer_items__asset__category',
            'transfer_items__original_department',
            'transfer_items__target_department',
            'approval_flows__approver'
        ),
        pk=pk
    )
    
    context = {
        'transfer': transfer,
        'can_approve': transfer.can_approve(request.user),
        'can_execute': transfer.can_execute(request.user),
    }
    
    return render(request, 'assets/transfer/transfer_detail.html', context)


@login_required
@require_http_methods(["POST"])
def transfer_submit(request, pk):
    """提交调拨申请"""
    transfer = get_object_or_404(AssetTransfer, pk=pk, applicant=request.user)
    
    if transfer.status != 'draft':
        messages.error(request, '只有草稿状态的申请才能提交')
        return redirect('assets:transfer_detail', pk=pk)
    
    transfer.status = 'pending'
    transfer.save()
    
    # 记录系统日志
    SystemLog.log(
        level='INFO',
        module='asset',
        action='transfer_submit',
        message=f'提交资产调拨申请: {transfer.transfer_number}',
        user=request.user,
        request=request,
        details={'transfer_id': transfer.id}
    )
    
    messages.success(request, '调拨申请已提交，等待审批')
    return redirect('assets:transfer_detail', pk=pk)


@login_required
@permission_required('assets.change_assettransfer', raise_exception=True)
def transfer_approve(request, pk):
    """审批调拨申请"""
    transfer = get_object_or_404(AssetTransfer, pk=pk)
    
    if not transfer.can_approve(request.user):
        messages.error(request, '您没有权限审批此调拨申请')
        return redirect('assets:transfer_detail', pk=pk)
    
    if request.method == 'POST':
        action = request.POST.get('action')
        notes = request.POST.get('notes', '')
        
        if action == 'approve':
            transfer.approve(request.user, notes)
            messages.success(request, '调拨申请已审批通过')
            
            # 记录系统日志
            SystemLog.log(
                level='INFO',
                module='asset',
                action='transfer_approve',
                message=f'审批通过资产调拨申请: {transfer.transfer_number}',
                user=request.user,
                request=request,
                details={'transfer_id': transfer.id, 'notes': notes}
            )
            
        elif action == 'reject':
            transfer.reject(request.user, notes)
            messages.success(request, '调拨申请已拒绝')
            
            # 记录系统日志
            SystemLog.log(
                level='INFO',
                module='asset',
                action='transfer_reject',
                message=f'拒绝资产调拨申请: {transfer.transfer_number}',
                user=request.user,
                request=request,
                details={'transfer_id': transfer.id, 'notes': notes}
            )
        
        return redirect('assets:transfer_detail', pk=pk)
    
    context = {
        'transfer': transfer,
    }
    
    return render(request, 'assets/transfer/transfer_approve.html', context)


@login_required
@permission_required('assets.change_asset', raise_exception=True)
def transfer_execute(request, pk):
    """执行调拨"""
    transfer = get_object_or_404(AssetTransfer, pk=pk)
    
    if not transfer.can_execute(request.user):
        messages.error(request, '调拨申请状态不正确或您没有执行权限')
        return redirect('assets:transfer_detail', pk=pk)
    
    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'start':
            transfer.start_execution(request.user)
            messages.success(request, '调拨执行已开始')
            
        elif action == 'complete':
            actual_cost = request.POST.get('actual_cost')
            try:
                with transaction.atomic():
                    transfer.complete(request.user, actual_cost)
                    messages.success(request, '调拨执行已完成')
                    
                    # 记录系统日志
                    SystemLog.log(
                        level='INFO',
                        module='asset',
                        action='transfer_complete',
                        message=f'完成资产调拨: {transfer.transfer_number}',
                        user=request.user,
                        request=request,
                        details={'transfer_id': transfer.id, 'actual_cost': actual_cost}
                    )
                    
            except Exception as e:
                messages.error(request, f'调拨执行失败: {str(e)}')
        
        return redirect('assets:transfer_detail', pk=pk)
    
    context = {
        'transfer': transfer,
    }
    
    return render(request, 'assets/transfer/transfer_execute.html', context)


@login_required
def my_transfer_requests(request):
    """我的调拨申请"""
    transfers = AssetTransfer.objects.filter(
        applicant=request.user
    ).select_related(
        'target_department', 'approver'
    ).prefetch_related('transfer_items')
    
    # 状态筛选
    status_filter = request.GET.get('status')
    if status_filter:
        transfers = transfers.filter(status=status_filter)
    
    # 分页
    paginator = Paginator(transfers, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'status_choices': AssetTransfer.TRANSFER_STATUS_CHOICES,
        'status_filter': status_filter,
    }
    
    return render(request, 'assets/transfer/my_requests.html', context)


@login_required
@permission_required('assets.change_assettransfer', raise_exception=True)
def pending_approvals(request):
    """待我审批的调拨"""
    # 这里可以根据业务规则定义哪些调拨需要当前用户审批
    transfers = AssetTransfer.objects.filter(
        status='pending'
    ).select_related(
        'applicant', 'applicant_department', 'target_department'
    ).prefetch_related('transfer_items')
    
    # 分页
    paginator = Paginator(transfers, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
    }
    
    return render(request, 'assets/transfer/pending_approvals.html', context)


@login_required
def transfer_analytics(request):
    """调拨分析统计"""
    from django.db.models import Count, Avg
    from datetime import datetime, timedelta
    
    # 基础统计
    total_transfers = AssetTransfer.objects.count()
    completed_transfers = AssetTransfer.objects.filter(status='completed').count()
    pending_transfers = AssetTransfer.objects.filter(status='pending').count()
    
    # 按状态统计
    status_stats = AssetTransfer.objects.values('status').annotate(
        count=Count('id')
    ).order_by('-count')
    
    # 按类型统计
    type_stats = AssetTransfer.objects.values('transfer_type').annotate(
        count=Count('id')
    ).order_by('-count')
    
    # 按月统计（最近12个月）
    monthly_stats = []
    for i in range(12):
        date = datetime.now() - timedelta(days=30*i)
        count = AssetTransfer.objects.filter(
            created_at__year=date.year,
            created_at__month=date.month
        ).count()
        monthly_stats.append({
            'month': date.strftime('%Y-%m'),
            'count': count
        })
    monthly_stats.reverse()
    
    # 平均处理时间
    avg_processing_time = AssetTransfer.objects.filter(
        status='completed',
        started_at__isnull=False,
        completed_at__isnull=False
    ).aggregate(
        avg_days=Avg('duration_days')
    )['avg_days']
    
    context = {
        'total_transfers': total_transfers,
        'completed_transfers': completed_transfers,
        'pending_transfers': pending_transfers,
        'completion_rate': round(completed_transfers / total_transfers * 100, 1) if total_transfers > 0 else 0,
        'status_stats': status_stats,
        'type_stats': type_stats,
        'monthly_stats': monthly_stats,
        'avg_processing_time': round(avg_processing_time, 1) if avg_processing_time else 0,
    }
    
    return render(request, 'assets/transfer/analytics.html', context)